<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\services\system;

use common\models\system\AdminDept;
use common\models\system\Dept;
use common\services\PermissionService;
use yii\db\Expression;

class DeptService
{

    /**
     * 获取某个用户的部门列表
     * @param int|string $userId
     * @param bool $valid 是否取有效的
     * @return array
     */
    public static function selectDeptByUserId($userId, $valid = false): array
    {
        if (!$userId) return [];
        $query = Dept::find()->alias('d')->select(['d.id', 'd.name', 'd.parent_id', 'd.status', 'd.list_sort'])
            ->leftJoin(AdminDept::tableName() . ' ad', 'ad.dept_id = d.id')
            ->where(['ad.admin_id' => $userId]);
        if ($valid) $query = $query->andWhere(['d.status' => 1]);
        $list = $query->orderBy('d.parent_id asc, d.list_sort asc, d.id asc')->distinct()->asArray()->all();
        return $list ?: [];
    }

    /**
     * 某个用户可选择列表
     * @param $userId
     * @param bool $valid 是否取有效的
     * @return array
     */
    public static function selectDeptUserSelectList($userId, $valid = false): array
    {
        if (PermissionService::isAdmin($userId)) return self::getList($valid);
        return self::selectDeptByUserId($userId, $valid);
    }

    /**
     * 当修改组织构架时，修改子类所有的parent_name和levels
     * @param $pid
     * @return bool
     */
    public static function updateChildExtendField($pid): bool
    {
        if (!$pid) return false;

        $parentInfo = Dept::findOne($pid);
        if (!$parentInfo) return false;
        $parent_name = trim($parentInfo->parent_name . ',' . $parentInfo->name, ',');
        $levels = trim($parentInfo->levels . ',' . $parentInfo->id, ',');

        foreach (Dept::find()->where(['parent_id' => $pid])->each() as $child) {
            if ($child->parent_name != $parent_name || $child->levels != $levels) {
                $child->parent_name = $parent_name;
                $child->levels = $levels;
                $res = $child->save(false);
                if ($res) self::updateChildExtendField($child['id']);
            }
        }
        return true;
    }

    /**
     * 获取某个组织的所有子组织
     * @param $id
     * @param false $onlyId
     * @return array
     */
    public static function getChildList($id, $onlyId = false): array
    {
        $list = [];
        if ($id > 0) {
            $list = Dept::find()->where(new Expression('FIND_IN_SET("' . $id . '",levels)'))->asArray()->all();
            if ($onlyId) $list = array_column($list, 'id');
        }
        return $list ?: [];
    }

    /**
     * 获取所有菜单，用于树形组件使用
     * @param bool $valid 是否取有效的
     * @return array
     */
    public static function getList($valid = false): array
    {
        $query = $list = Dept::find()->select(['id', 'parent_id', 'name', 'status']);
        if ($valid) $query = $query->where(['status' => 1]);
        $list = $query->orderBy('parent_id asc,list_sort asc,id asc')->asArray()->all();
        return $list ?: [];
    }
}
